package com.huya.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huya.common.result.PageResult;
import com.huya.mapper.PsychologicalTestMapper;
import com.huya.mapper.TestQuestionMapper;
import com.huya.pojo.dto.TestDTO;
import com.huya.pojo.dto.TestPageQueryDTO;
import com.huya.pojo.entity.PsychologicalTest;
import com.huya.pojo.entity.TestQuestion;
import com.huya.service.PsychologicalTestService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PsychologicalTestServiceImpl implements PsychologicalTestService {

    @Autowired
    private PsychologicalTestMapper psychologicalTestMapper;
    @Autowired
    private TestQuestionMapper testQuestionMapper;

    /**
     * 获取所有测试
     * @return
     */
    public List<PsychologicalTest> getAllTests() {
        return psychologicalTestMapper.selectAll();
    }


    /**
     * 根据测试id获取测试信息
     * @param testId
     * @return
     */
    public PsychologicalTest getTestById(Long testId) {
        return psychologicalTestMapper.selectTestById(testId);
    }


    /**
     * 分页查询测试列表
     * @param testPageQueryDTO
     * @return
     */
    public PageResult pageQuery(TestPageQueryDTO testPageQueryDTO) {
        PageHelper.startPage(testPageQueryDTO.getPage(), testPageQueryDTO.getPageSize());
        Page<PsychologicalTest> page = psychologicalTestMapper.pageQuery(testPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 新增测试
     * @param testDTO
     */
    @Transactional
    public void add(TestDTO testDTO) {
        //向测试元数据表中插入数据
        PsychologicalTest psychologicalTest = new PsychologicalTest();
        BeanUtils.copyProperties(testDTO, psychologicalTest);
        psychologicalTestMapper.insert(psychologicalTest);

        Long testId = psychologicalTest.getTestId();
        List<TestQuestion> testQuestions = testDTO.getTestQuestions();
        if(testQuestions != null && testQuestions.size() > 0){
            testQuestions.forEach(testQuestion -> {
                testQuestion.setTestId(testId);
        });
            testQuestionMapper.insertList(testQuestions);
        }
    }


    /**
     * 删除测试
     * @param testId
     */
    @Transactional
    public void delete(Long testId) {
        psychologicalTestMapper.deleteById(testId);
        testQuestionMapper.deleteByTestId(testId);
    }
}
